/**
 * onRef 父组件调用组件里的方法 默认onRef:()=>{}
 type: 1-主功能页面调用  2-穿透工作台调用                   
组件内部增加设置查询事件如下：
  settingAndSearch：type=2时父组件通过onRef调用settingAndSearch({productCode产品,date查询日期})方法，
  并传递产品code和查询日期,该函数对组件内的产品和查询日期赋值，并调用组件内部查询事件
 * 
 * */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DATA_ENTRY, AdvancedSearch, FirstHeaderC, NoQueryC } from '../../../comps';
import AssetsBig from './assetsBig'; // 资产大类
import Dimensionality from './dimensionality'; // 维度
import ProportionTrendChart from './proportionTrendChart'; // 占比趋势图
import MarketDetailed from './marketDetailed'; // 持仓明细
import Distribution from './distribution'; // 资产分配
import moment from 'moment';

@connect(({ assetAllocationM, keyFiguresM }) => ({
  assetAllocationM,
  keyFiguresM,
}))
@Form.create()
export default class AssetAllocationC extends PureComponent {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };

  state = {
    searchData: {},
    index: '',
    portfolioCode: '',
    portfolioCodeList: [],
    isShow: false,
    searchForm: null, // 表单实例
  };

  componentDidMount() {
    this.props.onRef(this);
    this.getStorageData();
  }

  componentDidUpdate(prevProps, prevState) {
    // 从用户视图跳转过来
    const data = sessionStorage.getItem('assetDeploy');
    sessionStorage.removeItem('assetDeploy');
    if (data) {
      const bondPositionsProduct = JSON.parse(data);
      // 查询变量赋值 以及表单赋值
      this.state.PRODUCTGROUPTREE?.props.form.setFieldsValue({
        portfolioCode: `${bondPositionsProduct.productCode} - ${bondPositionsProduct.productName}`,
      });
      this.setState(
        {
          bondPositionsProductCode: bondPositionsProduct.productCode,
        },
        () => {
          this.prodectChange({
            info: {
              portfolioCode: bondPositionsProduct.productCode,
              portfolioName: bondPositionsProduct.productName,
            },
          });
          //
          setTimeout(() => {
            this.searchData({
              needPenetrate: '0',
              portfolioCode: bondPositionsProduct.productCode,
              zqfz: '0',
              ...this.state.RANGEDATE?.props.form.getFieldsValue(),
            });
          }, 700);
        },
      );
    }
  }

  componentWillUnmount() {}

  // 搜索点击事件
  searchData = (e) => {
    if (e.portfolioCode) {
      // 有产品组合
      if (e.begin1 && e.begin2) {
        this.setState({
          isShow: true,
          searchData: {
            index: e.complextdate1,
            portfolioCode: this.state.portfolioCode,
            beginDate: e.begin1?.format('YYYY-MM-DD'),
            endDate: e.begin2?.format('YYYY-MM-DD'),
            needPenetrate: e.needPenetrate,
            zqfz: e.zqfz,
          },
        });
      } else {
        message.warning('请填写完整的查询条件');
        this.setState({
          beginDate: undefined,
          endDate: undefined,
        });
      }
    } else if (this.state.portfolioCodeList.length > 0) {
      // 有产品组
      if (e.begin1 && e.begin2) {
        this.setState({
          searchData: {
            index: e.complextdate1,
            portfolioCodeList: this.state.portfolioCodeList,
            beginDate: e.begin1.format('YYYY-MM-DD'),
            endDate: e.begin2.format('YYYY-MM-DD'),
            needPenetrate: e.needPenetrate,
            zqfz: e.zqfz,
          },
          isShow: true,
        });
      } else {
        message.warning('请填写完整的查询条件');
        this.setState({
          beginDate: undefined,
          endDate: undefined,
        });
      }
    } else {
      message.warning('请填写完整的查询条件');
    }
  };

  // 产品组改变
  handPortfolioCodeListChange = (e) => {
    if (e) {
      this.state.searchForm?.resetFields(['portfolioCode']); // 重置组合和产品
      this.state.RANGEDATE.reset();
      if (e?.info?.children.length > 0) {
        this.setState({
          portfolioCodeList: e?.info?.children.map((x) => x.code),
          portfolioCode: '',
        });
      } else {
        message.warning('该组合下无产品');
        this.setState({
          portfolioCodeList: [],
          portfolioCode: '',
        });
      }
    } else {
      this.state.RANGEDATE.reset();
      this.setState({
        portfolioCodeList: [],
        portfolioCode: '',
      });
    }
  };

  // 产品名称改变
  prodectChange = (e) => {
    if (e) {
      const data = e.info;
      this.state.searchForm?.resetFields(['portfolioCodeList']);
      this.setState({
        portfolioCode: data.portfolioCode,
        portfolioCodeList: [],
        portfolioName: data.portfolioName,
      });
    } else {
      this.setState(
        {
          portfolioCode: '',
          portfolioCodeList: [],
        },
        () => {
          this.state.RANGEDATE.reset();
        },
      );
    }
  };

  // 从组合概览跳转   拿到sessionStorage中的查询条件
  getStorageData = () => {
    // 组合概览搜索栏数据
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    // 资产配置证券负债正负
    const savezqfzData = JSON.parse(sessionStorage.getItem('changeSavezqfz'));
    if (overviewData) {
      const { portfolioCode, timeRange, beginDate, endDate, needPenetrate } = overviewData;

      this.setState({
        portfolioCode,
        timeRange,
        beginDate,
        endDate,
        savezqfzData, // 负债占比
        needPenetrate, // 是否穿透
      });
    }
  };

  // 获取子组件接口返回的数据用于匹配code
  changePortfolioCodeInitValue = (data) => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));

    sessionStorage.removeItem('searchObj');
    sessionStorage.removeItem('changeSavezqfz');
    const { portfolioCode } = overviewData || {};
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.portfolioCode === portfolioCode) {
        this.setState(
          {
            codeKey: item.key,
          },
          () => {
            // 更新数据完成之后触发查询
            const { codeKey, needPenetrate, savezqfzData, beginDate, endDate, timeRange } = this.state;
            const changeSearchData = {
              zqfz: savezqfzData || '0',
              needPenetrate,
              beginDate: moment(beginDate),
              endDate: moment(endDate),
              timeRange,
              complextdate1: timeRange,
              portfolioCode: codeKey,
              begin1: moment(beginDate),
              begin2: moment(endDate),
            };
            this.searchData(changeSearchData);
          },
        );
      }
    }
  };

  render() {
    const { searchData, codeKey, beginDate, endDate, timeRange, savezqfzData, needPenetrate } = this.state;
    console.log('beginDate', beginDate);
    const { type } = this.props;
    const args = {
      portfolioCode: searchData.portfolioCode,
      portfolioCodeList: searchData.portfolioCodeList || [],
      timeRange: searchData.index || '0',
      beginDate: searchData.beginDate,
      endDate: searchData.endDate,
      needPenetrate: searchData.needPenetrate,
      zqfz: searchData.zqfz,
    };
    const searchProps = {
      parentId: this.props.parentId,
      dataSource: [
        {
          dataIndex: 'portfolioCodeList',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          multiple: false,
          onRef: (ref) => this.setState({ PRODUCTGROUP: ref }),
          onChange: this.handPortfolioCodeListChange,
          hide: type == 2,
        },
        {
          dataIndex: 'portfolioCode',
          title: type == 2 ? '产品名称' : '产品',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          multiple: false,
          onRef: (ref) => this.setState({ PRODUCTGROUPTREE: ref }),
          onChange: this.prodectChange,
          changePortfolioCodeInitValue: this.changePortfolioCodeInitValue,
          initialValue: codeKey,
        },
        this.state.portfolioCode
          ? {
              selectIndex: 'complextdate1',
              startIndex: 'begin1',
              endIndex: 'begin2',
              title: '时间区间',
              type: DATA_ENTRY.HOlDDATERANGEC,
              productCode: this.state.portfolioCode,
              defaultType: timeRange || '2',
              flag: '2',
              initialValue: beginDate && { beginDate: moment(beginDate), endDate: moment(endDate) },
            }
          : {
              type: DATA_ENTRY.RANGEDATE,
              dataIndex: ['begin1', 'begin2'],
              title: '时间区间',
              disabled: !this.state.portfolioCodeList.length > 0,
              onRef: (ref) => this.setState({ RANGEDATE: ref }),
            },
        {
          dataIndex: 'needPenetrate',
          title: '是否穿透',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: needPenetrate || (type == 2 ? '1' : '0'),
        },
        {
          dataIndex: 'zqfz',
          title: '证券负债',
          type: DATA_ENTRY.SELECT,
          initialValue: savezqfzData || '0',
          dataSource: [
            { title: '占比为正', value: '1' },
            { title: '占比为负', value: '0' },
          ],
        },
      ],
      onQuery: (e) => {
        this.searchData(e);
      },
      onClear: () => {
        // this.state.COMPLEXDATE.setSelctAndDate("", "", "");
        // this.state.COMPLEXDATE.setSelctAndDate("", "", "");
        this.setState({
          portfolioCode: '',
          portfolioCodeList: [],
          codeKey: '',
          timeRange: '',
          savezqfzData: '',
          needPenetrate: '',
        });
      },
    };

    const { isShow } = this.state;
    return (
      <div>
        <div>
          <AdvancedSearch {...searchProps} onRef={(ref) => this.setState({ searchForm: ref.props.form })} />
        </div>

        {isShow ? (
          <div>
            {args.portfolioCodeList.length > 0 && (
              <div style={{ marginTop: '10px' }}>
                <Distribution args={args} />
              </div>
            )}

            <div style={{ marginTop: '10px' }}>
              <FirstHeaderC title='组合持仓统计' />

              <AssetsBig args={args} type={type} />
              <ProportionTrendChart args={args} />
            </div>
            <div style={{ marginTop: '10px' }}>
              <div>
                <Dimensionality args={args} type={type} />
              </div>
            </div>
            <div style={{ marginTop: '10px', marginBottom: '20px' }}>
              <div>
                <MarketDetailed args={args} type={type} />
              </div>
            </div>
          </div>
        ) : (
          <div style={{ marginTop: '20px' }}>
            <NoQueryC />
          </div>
        )}
      </div>
    );
  }
}
